import fse from 'fs-extra';
import handlebars from 'handlebars';
import path from 'path';

import { ICaseRecord, ITaskReport } from './report-models';

/**
 * 生成报告文件的类
 */
class ReportBuilder {
  /**
   * 单用例报告文件编译函数
   *
   * @type {HandlebarsTemplateDelegate}
   */
  readonly caseReportBuilder: HandlebarsTemplateDelegate;

  /**
   * 任务报告编译函数
   *
   * @type {HandlebarsTemplateDelegate}
   */
  readonly taskReportBuilder: HandlebarsTemplateDelegate;

  constructor() {
    handlebars.registerHelper('link', function (text: string, url: string) {
      const newUrl = handlebars.escapeExpression(url);
      const newText = handlebars.escapeExpression(text);
      return new handlebars.SafeString(`<a href='${newUrl}'>${newText}</a>`);
    });
    const templateDir = path.join(__dirname, 'report-template');
    this.caseReportBuilder = handlebars.compile(
      fse.readFileSync(path.join(templateDir, 'caseReport.html'), 'utf-8'));
    this.taskReportBuilder = handlebars.compile(
      fse.readFileSync(path.join(templateDir, 'taskReport.html'), 'utf-8'));
  }

  /**
   * 生成单用例报告
   *
   * @param {ICaseRecord} data
   * @return {Promise<void>}
   */
  async buildCaseReport(data: ICaseRecord) {
    const report = this.caseReportBuilder(data);
    await fse.writeFile(data.reportPath!, report);
  }

  /**
   * 生成任务报告
   *
   * @param {ITaskReport} data
   * @return {Promise<void>}
   */
  async buildTaskReport(data: ITaskReport) {
    const report = this.taskReportBuilder({
      ...data,
      records: Object.entries(data.records)
    });
    await fse.writeFile(data.reportPath!, report);
  }
}

export const reportBuilder: ReportBuilder = new ReportBuilder();
